package data

import (
	"log"
	"os"
	"strconv"
	"strings"
	"time"
)

// 一般显示40条消息发给前端
// 每1分钟保存一次文件
// 内存中达到1040条时，把前1000条保存到文件中，内存中只保留40条
var MemSaveMax = 1000
var FileSavePath = "msg"
var saveLoopTick = time.Tick(time.Minute)
var saveTick chan struct{}
var nowFileName = time.Now().Format("2006-01-02-15-04-05") + ".txt"

type Message struct {
	Sender  int    `json:"sender"`
	Content string `json:"content"`
}

var Messages = make([]Message, 0)

func AddMessage(sender int, message string) {
	lock()
	Messages = append(Messages, Message{Sender: sender, Content: message})
	if len(Messages) >= MemSaveMax+40 {
		saveTick <- struct{}{}
	}
	unlock()
}

func GetLatestMessages() []Message {
	len := len(Messages)
	if len > 40 {
		return Messages[len-40:]
	} else {
		return Messages
	}
}

func SaveMessagesThread() {
	os.Mkdir(FileSavePath, 666)
	for {
		select {
		case <-saveLoopTick:
		case <-saveTick:
		}
		strOutBuilder := strings.Builder{}
		if len(Messages) >= MemSaveMax+40 {
			for _, m := range Messages[:MemSaveMax] {
				strOutBuilder.WriteString(strconv.Itoa(m.Sender) + ": " + m.Content + "\n")
			}
		} else {
			for _, m := range Messages {
				strOutBuilder.WriteString(strconv.Itoa(m.Sender) + ": " + m.Content + "\n")
			}
		}
		filePutContents(FileSavePath+"/"+nowFileName, strOutBuilder.String())
		log.Println("聊天消息已备份至" + FileSavePath + "/" + nowFileName)
		if len(Messages) >= MemSaveMax+40 {
			Messages = Messages[MemSaveMax:]
			nowFileName = time.Now().Format("2006-01-02-15-04-05") + ".txt"
		}
	}
}
